package com.lw.leetcode.add.e;

/**
 * Created with IntelliJ IDEA.
 * 6365. 将整数减少到零需要的最少操作数
 *
 * @author liw
 * @version 1.0
 * @date 2023/2/20 9:30
 */
public class MinOperations {

    public static void main(String[] args) {
        MinOperations test = new MinOperations();

        // 3
//        int n = 39;

        // 3
//        int n = 54;

        // 4
        int n = 8433;

        int i = test.minOperations(n);
        System.out.println(i);
    }

    public int minOperations(int n) {
        System.out.println(Integer.toBinaryString(n));
        if ((n & 1) == 0) {
            while ((n & 2) != 2) {
                n >>= 1;
            }
        }
        int all = Integer.bitCount(n);
        int a = 0;
        int b = 0;
        int min = all;
        while (n != 0) {
            if ((n & 1) == 1) {
                a++;
            } else {
                b++;
            }
            min = Math.min(min, all - a + (b == 0 ? 2 : b + 1));
            n >>= 1;
        }
        return Math.min(min, (b == 0 ? 2 : b + 1));
    }

}
